<%@page contentType="text/html;charset=UTF-8" import="
    javax.jcr.Node,
    javax.jcr.Session"
%><%@taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling/1.0"%><%
%><sling:defineObjects/><%!

/* Checks that the string is not emtpy */
public static boolean isValid(final String str) {
    return (str != null && str.length() > 0);
}

/* Checks that the string is not emtpy and that the email is valid */
public static boolean isValidEmail(final String email) {
    return isValid(email) && email.matches("^[a-zA-Z0-9_\\-\\+]+(?:\\.[a-zA-Z0-9_\\-\\+]+)*@[a-zA-Z0-9_\\-\\+]+(?:\\.[a-zA-Z0-9_\\-\\+]+)+$");
}

%><%

String name    = request.getParameter("name").trim();
String email   = request.getParameter("email").trim();
String content = request.getParameter("content").trim();

if (isValid(name) && isValidEmail(email) && isValid(content)) {
    
    // In a real-life case, you'd need to create an admin session instead
    final Session jcrSession = currentNode.getSession();
    
    // Creat a unique node name
    String nodeName = name.toLowerCase().replaceAll("[^a-zA-Z0-9\\_\\-]+", "-");
    if (nodeName.length() > 32) {
        nodeName = nodeName.substring(0, 32);
    }
    if (currentNode.hasNode(nodeName)) {
        for (int i = 1; i < 100; ++i) {
            if (!currentNode.hasNode(nodeName+"-"+i)) {
                nodeName = nodeName+"-"+i;
                break;
            }
        }
    }
    
    // Create the node and set it's properties
    Node node = currentNode.addNode(nodeName);
    node.setProperty("sling:resourceType", "movies/components/comment");
    node.setProperty("name", name);
    node.setProperty("email", email);
    node.setProperty("content", content);
    
    jcrSession.save();
    // In a real-life case, you'd need to close again the admin session here
}

response.sendRedirect(request.getRequestURI());

%>